<template>
    <view class="modal bottom-modal" :class="show ? 'show' : ''">
        <view class="dialog" style="border-radius: 8px 8px 0px 0px;">
            <view class="bar bg-white" style="justify-content: flex-end;">
                <view class="action text-blue" @tap="cameraError">关闭</view>
            </view>
            <view>
                <view class="detectInfo">{{ isSuccess ? '人脸检测成功' : tipsText}}</view>
                <view class="faceContent">
                    <camera v-if="show && !isSuccess" device-position="front" resolution="high" @stop="cameraError" @error="cameraError" style="width: 600rpx;height: 600rpx;border-radius: 50%;position: absolute;top: 0;left: 50%;transform: translateX(-50%);" />
                    <view class="successImage" v-if="isSuccess">
                        <!-- <img src="../../static/authSucceed.png"> -->
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// 人脸检测
/**
 * @event {Function} photoChange 拍照完成事件
 * @event {Function} detectFailed 人脸检测失败
 * @event {Function} detectOver 人脸检测结束
 * 
 * @method {Function} detectOver 人脸检测完成
 * @method {Function} initData 初始化人脸检测
 */
export default {
    name: 'face-detect',
    data() {
        return {
            show: false,
            tipsText: '检测不到人脸',
            isSuccess: false, //是否检测完成
        }
    },
    methods: {
        // 核验失败
        cameraError(e){
            this.hideModal()
            this.$emit('detectFailed')
        },
        // 关闭
        hideModal(){
            wx.stopFaceDetect()
            this.show = false
            this.tipsText = '检测不到人脸'
            this.isSuccess = false
        },
        // 拍照
        takePhoto() {
            const context = uni.createCameraContext();
            context.takePhoto({
                quality: 'normal',
                success: (res) => {
                    uni.getNetworkType({
                        success: (network) => {
                            if(network.networkType != 'none' ){
                                // 图片路径
                                this.$emit('photoChange',res.tempImagePath)
                            }else{
                                this.tipsText = '无网络，请确保网络为开启状态'
                            }
                        },
                        fail: (error) => {
                            this.tipsText = '当前网络异常，请稍后重试'
                        }
                    });
                }
            });
        },


        // 检测完成
        detectOver(){
            this.isSuccess = true
            let t = setTimeout(() => {
                this.hideModal()
                clearTimeout(t)
                this.$emit('detectOver')
            }, 2000);
        },
        initData() {
            wx.getSetting({
                success: (res) => {
                    if (res.authSetting['scope.camera']) {
                        this.faceDetect()
                    } else {
                        wx.authorize({
                            scope: 'scope.camera',
                            success: () => {
                                this.faceDetect()
                            },
                            fail:(error) => {
                                wx.showToast({title: '授权失败',icon: 'none',})
                            }
                        })
                    }
                },
                fail: (error) => {
                    wx.showToast({title: '获取用户授权信息失败',icon: 'none',})
                }
            })
        },
        // 初始化人脸检测
        faceDetect(){
            this.show = true
            wx.initFaceDetect()
            const context = wx.createCameraContext()
            const listener = context.onCameraFrame((frame) => {
                wx.faceDetect({
                    frameBuffer: frame.data,
                    width: frame.width,
                    height: frame.height,
                    enablePoint: true,
                    enableConf: true,
                    enableAngle: true,
                    enableMultiFace: true,
                    success: (faceData) => {
                        let face = faceData.faceInfo[0]
                        if(faceData.x == -1 || faceData.y == -1) {
                            this.tipsText = '检测不到人脸'
                        }
                        if(faceData.faceInfo.length > 1) {
                            this.tipsText = '请保证只有一人做核验'
                        } else {
                            if(face.angleArray.pitch >= 0.1 || face.angleArray.roll >= 0.1 || face.angleArray.yaw >= 0.1) {
                                this.tipsText = '请平视摄像头'
                            } else if(face.confArray.global <= 0.8 || face.confArray.leftEye <= 0.8 || face.confArray.mouth <= 0.8 || face.confArray.nose <= 0.8 || face.confArray.rightEye <= 0.8) {
                                this.tipsText = '请勿遮挡五官'
                            } else {
                                this.tipsText = '正在核验，请保持'
                                this.takePhoto()
                                wx.stopFaceDetect()
                            }
                        }
                    },
                    fail: (err) => {
                        if(err.x == -1 || err.y == -1) {
                            this.tipsText = '检测不到人脸'
                        }
                    }
                })
            })
            listener.start()
        }
    }
}
</script>

<style scoped>
.modal {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	z-index: 1110;
	opacity: 0;
	outline: 0;
	text-align: center;
	-ms-transform: scale(1.185);
	transform: scale(1.185);
	backface-visibility: hidden;
	perspective: 2000rpx;
	background: rgba(0, 0, 0, 0.6);
	transition: all 0.3s ease-in-out 0s;
	pointer-events: none;
}
.modal::before {
	content: "\200B";
	display: inline-block;
	height: 100%;
	vertical-align: middle;
}
.modal.show {
	opacity: 1;
	transition-duration: 0.3s;
	-ms-transform: scale(1);
	transform: scale(1);
	overflow-x: hidden;
	overflow-y: auto;
	pointer-events: auto;
}
.modal.bottom-modal::before {
	vertical-align: bottom;
}

.modal.bottom-modal .dialog {
	width: 100%;
	border-radius: 0;
}

.modal.bottom-modal {
	margin-bottom: -1000rpx;
}

.modal.bottom-modal.show {
	margin-bottom: 0;
}

.dialog {
	position: relative;
	display: inline-block;
	vertical-align: middle;
	margin-left: auto;
	margin-right: auto;
	width: 680rpx;
	max-width: 100%;
	background-color: #f8f8f8;
	border-radius: 10rpx;
	overflow: hidden;
}
.bar {
	display: flex;
	position: relative;
	align-items: center;
	min-height: 100rpx;
    padding: 0rpx 40rpx;
	justify-content: space-between;
}
.bg-white {
	background-color: #ffffff;
	color: #666666;
}
.action {
	color: #0081ff;
}

image{
    width: 100%;
    height: 100%;
}
.detectInfo{
    padding: 100rpx 0rpx;
    font-size: 34rpx;
    text-align: center;
}
.faceContent{
    height: 700rpx;
    position: relative;
}
.successImage{
    overflow: hidden;
    width: 600rpx;
    height: 600rpx;
    border-radius: 50%;
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
}
</style>